package com.lagou.zk;

import com.lagou.client.RPCConsumer;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.stereotype.Component;

import java.util.HashSet;

/**
 * @author wuyuhan
 * @date 2021/1/10 15:24
 */
public class MyClient {

    //创建连接实例
    private CuratorFramework client = null;
//
//    private HashSet<String> address = new HashSet<>();

    public static String rootPath = "/lg-zkClient";



    public MyClient() throws Exception {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        //使用fluent编程风格
        CuratorFramework base = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181")
                .sessionTimeoutMs(50000)
                .connectionTimeoutMs(30000)
                .retryPolicy(retryPolicy)
                .build();
        this.client = base;


    }

    public void start(RPCConsumer rpcConsumer) throws Exception {
        //启动
        client.start();
        System.out.println("会话创建完成。。");
        PathChildrenCache pathChildrenCache = registerPathChildListener(rootPath, new NodeListener(rpcConsumer));
    }

    public PathChildrenCache registerPathChildListener(String nodePath, PathChildrenCacheListener listener) {
        try {
            //1. 创建一个PathChildrenCache
            PathChildrenCache pathChildrenCache = new PathChildrenCache(client, nodePath, true);

            //2. 添加目录监听器
            pathChildrenCache.getListenable().addListener(listener);

            //3. 启动监听器
            pathChildrenCache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);

            //4. 返回PathChildrenCache
            return pathChildrenCache;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
